package com.yzt.javacv;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.imageio.ImageIO;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

/**
 * @author Yang_ZT 
 *
 */
public class VideoScreenshots {

	public static synchronized boolean screenshots(String filePath) {
		try {
			File file = new File(filePath);
			if (!file.isFile() || !file.exists()) {
				App.jTextArea.append(App.sdf.format(new Date()) + "--文件路径不正确，请重试...\n");
				App.jScrollBar.setValue(App.jScrollBar.getMaximum());
				return false;
			}

			String fileName = file.getName();
			String targetFileName = fileName.substring(0, fileName.lastIndexOf(".")) + "_cut.jpg";
			File targetFile = new File(file.getParentFile(), targetFileName);

			if (file.exists() && file.isFile()) {
				App.jTextArea.append(App.sdf.format(new Date()) + "--文件路径正确，正在进行截图.....\n");
				App.jScrollBar.setValue(App.jScrollBar.getMaximum());
				FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
				ff.start();
				int ftp = ff.getLengthInFrames();
				int flag = 0;
				Frame frame = null;
				while (flag <= ftp) {
					// 获取帧
					frame = ff.grabImage();
					// 过滤前3帧，避免出现全黑图片
					if ((flag > App.GLOBAL_FRAMES) && (frame != null)) {
						break;
					}
					flag++;
				}
				ImageIO.write(FrameToBufferedImage(frame), "jpg", targetFile);
				ff.stop();
				ff.close();
			}
			App.jTextArea.append(App.sdf.format(new Date()) + "--视频第一帧截取成功,请在视频当前目录查找！！\n");
			App.jScrollBar.setValue(App.jScrollBar.getMaximum());
		} catch (IOException e) {
			App.jTextArea.append(App.sdf.format(new Date()) + "--视频文件有损坏或不是视频文件，请重新选择文件......\n");
			App.jScrollBar.setValue(App.jScrollBar.getMaximum());
		}
		return true;
	}

	private static RenderedImage FrameToBufferedImage(Frame frame) {
		// 创建BufferedImage对象
		Java2DFrameConverter converter = new Java2DFrameConverter();
		BufferedImage bufferedImage = converter.getBufferedImage(frame);
		return bufferedImage;
	}
}
